import { Component, OnInit } from '@angular/core';
import {Message, TreeNode} from 'primeng/primeng';
import {DutyService} from '../duty.service';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {environment} from '../../../environments/environment';
import { StorageService } from '../../services/storage.service';
import {PublicService} from '../../services/public.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-schedule-add',
  templateUrl: './schedule-add.component.html',
  styleUrls: ['./schedule-add.component.scss'],
})
export class ScheduleAddComponent implements OnInit {

    zh: any;                               // 汉化
    initStartTime: Date;                   // 当日系统时间
    beginTime: Date;                       // 开始时间
    endTime: Date;                         // 结束时间
    shiftSearchOptions: any[];             // 排班班次数据
    shiftSelectedMultipleOption: any[];    // 排班班次已选数据
    relativeSearchOptions: any[];          // 关联计划数据
    relativeSelectedMultipleOption: any[]; // 关联计划已选数据
    approveOid: string;                    // 审批OID
    approveSearchOptions: any[];           // 审批人数据
    approveSelectedMultipleOption: any[];  // 审批人已选数据
    defaultId: string;                     // 新增排班编号
    defaultCreator: string;                // 新增排班创建人
    defaultCreateTime: string;             // 新增排班创建时间
    departementDisplay: boolean;           // 部门组织树显示控制
    selectedDepartment = '';               // 表单显示的已选中的部门组织
    newSchdule: FormGroup;
    msgs: Message[] = [];                  // 验证消息提示
    msgPop: Message[] = [];                // 验证消息弹框提示
    hadSaved: boolean;                     // 保存是否成功
    hadDownload: boolean;                  // 生成排班表是否成功
    downloadBtn: boolean;                   // 导入按钮是否显示
    saved: boolean;                         // 保存按钮是否显示
    uploadIp: string;                       // 上传接口
    progressBar: boolean;                  // 进度条
    filesTree4: TreeNode[] = [];                // 部门组织初始
    selected: TreeNode[];                  // 部门组织结束
    selectedStr = '';                      // 部门选中的OID字符串
    minEndTime: Date;


    constructor(private dutyService: DutyService,

    private storageService: StorageService,
        private publicService: PublicService,
        private router: Router,
        private fb: FormBuilder) {
    }

    ngOnInit() {
        this.createForm();
        this.uploadIp = `${environment.url.management}/onduty/upload`;
        this.departementDisplay = false;
        this.initStartTime = new Date();
        this.beginTime = new Date();
        this.endTime = new Date();
        this.hadSaved = true;
        this.hadDownload = true;
        this.downloadBtn = false;
        this.progressBar = true;
        this.saved = false;
        this.zh = this.initZh();
        this.approveOid = '';
        this.dutyService.getDepartmentDatas().subscribe(res => {
            this.filesTree4 = res;
        });
        this.defaultCreateTime = ScheduleAddComponent.formatDate(new Date());
    }

    initZh() {
        return  {
          firstDayOfWeek: 1,
          dayNames: [ '周一', '周二', '周三', '周四', '周五', '周六', '周日' ],
          dayNamesShort: [ '一', '二', '三', '四', '五', '六', '七' ],
          dayNamesMin: [ '一', '二', '三', '四', '五', '六', '七' ],
          monthNames: [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ],
          monthNamesShort: [ '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二' ],
        };
    }

    // 部门组织树模态框
    showTreeDialog() {
        this.selected = [];
        this.departementDisplay = true;
    }

    // 日期格式化
    static formatDate(date) {
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      m = m < 10 ? '0' + m : m;
      let d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      return y + '-' + m + '-' + d;
    }

    // 组织树懒加载
    nodeExpand(event) {
        // console.log(event.node);
        if (event.node) {
            this.dutyService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
                event.node.children  = res;
            });
        }
    }

    clearTreeDialog () {
        this.selectedDepartment = '';
        let query = '';
        this.publicService.getApprovers(this.selectedStr).subscribe(res => {
            this.approveSearchOptions =  this.approveSearchOptions = this.filterCountry(query, res);
        });
    }

    closeTreeDialog() {
        let selectedOid: Array<any> = [];
        let selectedName: Array<any> = [];
        let query = '';
        this.approveSelectedMultipleOption = [];
        // console.log(this.selected);
        for (let val of this.selected) {
            selectedOid.push(val['oid']);
            selectedName.push(val['label']);
        }
        this.selectedStr = selectedOid.join(',');
        this.selectedDepartment = selectedName.join(',');
        this.publicService.getApprovers(this.selectedStr).subscribe(res => {
            this.approveSearchOptions =  this.approveSearchOptions = this.filterCountry(query, res);
        });
        // console.log(this.selectedStr );

        this.departementDisplay = false;
    }

    createForm() {
        this.newSchdule = this.fb.group({
            scheduleId: ['', Validators.required],
            scheduleCreator: ['', Validators.required],
            schduleName: ['', Validators.required],
            scheduleCreateTime: [this.defaultCreateTime, Validators.required],
            scheduleApprovor: [this.approveSelectedMultipleOption],
            schduleDepartment: ['', Validators.required],
            schduleStart: ['', Validators.required],
            schduleEnd: ['', Validators.required],
            schduleShift: ['', Validators.required],
            schduleRelative: ['', Validators.required]
        });
    }

    get isName() {
        return !this.newSchdule.controls['schduleName'].untouched && (!this.newSchdule.controls['schduleName'].valid);
    }

    filterApproverMultiple(event) {
        // console.log(this.approveOid);
        let query = event.query;
        this.publicService.getApprovers(this.selectedStr).subscribe(res => {
            this.approveSearchOptions = this.filterCountry(query, res);
        });
    }

    filterShiftMultipe(event) {
        let query = event.query;
        this.dutyService.getAllSchduleShifts().subscribe(res => {
            this.shiftSearchOptions = this.filterCountry(query, res);
        });
    }

    filterRelativeMutipe(event) {
        let query = event.query;
        this.dutyService.getRelaticeScheduleData().subscribe(res => {
            this.relativeSearchOptions = this.filterCountry(query, res);
        });
    }

    showError() {
        this.msgs = [];
        this.msgs.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
    }

    submit() {
        let selectedArray = [];
        if ( this.selected ) {
            for ( let i = 0; i < this.selected.length; i++ ) {
                selectedArray[i] = {
                    oid: this.selected[i]['oid'],
                    name: this.selected[i]['label']
                };
            }
        }

        this.msgs = [];
        if ( (!this.newSchdule.get('schduleName').value)
            || !this.defaultCreateTime
            || !this.approveSelectedMultipleOption
            || !this.shiftSelectedMultipleOption
            || !this.selectedDepartment) {
                 this.showError();
        }else if ( this.beginTime.toString() === this.endTime.toString()) {
            this.msgs = [];
            this.msgs.push({severity: 'error', summary: '错误消息提示', detail: '起始时间和结束时间不能相同'});
        } else {
            this.dutyService.addSchedule(this.newSchdule.get('schduleName').value,
                this.defaultCreateTime,
                selectedArray,
                this.approveSelectedMultipleOption,
                ScheduleAddComponent.formatDate(this.beginTime),
                ScheduleAddComponent.formatDate(this.endTime),
                this.shiftSelectedMultipleOption,
                this.relativeSelectedMultipleOption,
                '草稿').subscribe(res => {
                if ( res['errcode'] === '00000' ) {
                    this.defaultId = res['data'].did;
                    this.defaultCreator = res['data'].creator;
                    this.msgPop = [];
                    this.hadSaved = false;
                    this.msgPop.push({severity: 'success', summary: '消息提示', detail: '计划保存成功'});
                    this.saved = true;
                }else {
                    this.msgPop = [];
                    this.msgPop.push({severity: 'error', summary: '提示消息', detail: '计划保存失败' + '\n' + res });
                }
            });
        }
    }

    filterCountry(query, countries: any[]): any[] {
        let filtered: any[] = [];
        for (let i = 0; i < countries.length; i++) {
            let country = countries[i];
            if (country.name.toLowerCase().indexOf(query.toLowerCase()) === 0) {
                filtered.push(country);
            }
        }
        return filtered;
    }

    downloadModel() {
        this.progressBar = false;
        this.dutyService.downloadModel(this.defaultId).subscribe(res => {
            if (!res) {
                this.progressBar = true;
                this.msgPop = [];
                this.msgPop.push({severity: 'error', summary: '提示消息', detail: '模板生成失败' });
            }else {
                this.progressBar = true;
                this.msgPop = [];
                this.hadDownload = false;
                this.downloadBtn = true;
                window.open(`${environment.url.management}/${res}`, '_blank');
                this.msgPop.push({severity: 'success', summary: '消息提示', detail: '模板生成成功！请在本地文件夹中查看'});
            }
        });
    }

    onBeforeUpload(event) {
        let token = this.storageService.getToken('token');
        event.formData.append('access_token', token);
        event.formData.append('id', this.defaultId);
    }

    onUpload(event) {
        let res = JSON.parse(event.xhr.response);
        if ( res['errcode'] === '00000') {
            this.msgPop = [];
            this.msgPop.push({severity: 'success', summary: '消息提示', detail: '计划导入成功'});
            window.setTimeout(() => {
                this.router.navigateByUrl('index/duty/manage');
            }, 1100);
        }else {
            this.msgPop = [];
            this.msgPop.push({severity: 'error', summary: '提示消息', detail: '计划导入失败' + res['errmsg'] });
        }
    }

    onBasicUpload(event) {
        // console.log(event);
    }

    startTimeSelected(t) {
        this.endTime = t;
        this.minEndTime = t;
        // console.log( this.endTime);
    }

}
